<?php

namespace app\common\model;


use PDOStatement;
use think\Collection;

class ProductSpec extends BaseModel
{
    protected $pk = 'spec_id';

    /**
     * 属性名称是否存在
     * @param string $name 分类名
     * @return bool
     * @date 2020/09/11
     * @author longli
     */
    public static function hasByName($name)
    {
        return !!static::where(['name' => $name])->count();
    }

    /**
     * 规格中文名是是否存在
     * @param string $nameCh 规格中文名
     * @return bool
     * @date 2020/09/15
     * @author longli
     */
    public static function hasByNameCh($nameCh)
    {
        return !!static::where(['name_ch' => $nameCh])->count();
    }

    /**
     * 通过名称获取单条数据
     * @param string $name
     * @return ProductSpec|null
     * @date 2020/09/12
     * @author longli
     */
    public static function getByName($name = '')
    {
        $s = self::getByNames([$name]);
        return !empty($s) ? $s[0] : null;
    }

    /**
     * 获取名称获取一组数据
     * @param array $names
     * @return array|PDOStatement|string|Collection
     * @date 2020/09/12
     * @author longli
     */
    public static function getByNames($names = [])
    {
        return static::where([
            ['name', 'in', $names],
            ['status', 'eq', self::IS_YES]
        ])->select();
    }

    /**
     * 更新规格信息
     * @param int|int[] $ids 规格 id
     * @param array $data 规格信息
     * @return bool
     * @date 2020/09/14
     * @author longli
     */
    public static function editBySpecId($ids, $data)
    {
        try
        {
            foreach(static::where("spec_id", "in", $ids)->select() as $spec)
            {
                $spec->save($data);
            }
            return true;
        }catch(\Exception $e)
        {
            return false;
        }
    }

    /**
     * 获取所有规格
     * @return array|\PDOStatement|string|\think\Collection
     * @date 2020/09/15
     * @author longli
     */
    public static function getAll()
    {
        return static::where(['status' => self::IS_YES])->order("type, sort desc, spec_id desc")->select();
    }
}
